package com.demo.petshop.service.impl;

import com.demo.petshop.entity.*;
import com.demo.petshop.mapper.*;
import com.demo.petshop.service.SearchService;
import com.demo.petshop.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.demo.petshop.entity.table.CartItemsTableDef.CART_ITEMS;
import static com.demo.petshop.entity.table.FavoritesTableDef.FAVORITES;
import static com.demo.petshop.entity.table.OrderItemsTableDef.ORDER_ITEMS;
import static com.demo.petshop.entity.table.OrdersTableDef.ORDERS;
import static com.demo.petshop.entity.table.ProductsTableDef.PRODUCTS;
import static com.demo.petshop.entity.table.StoresTableDef.STORES;
import static com.demo.petshop.entity.table.VideosTableDef.VIDEOS;

@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Search> implements SearchService {
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private StoresMapper storesMapper;
    @Autowired
    private VideosMapper videosMapper;
    @Autowired
    private CartItemsMapper cartItemsMapper;
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
    private FavoritesMapper favoritesMapper;

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }


    @Override
    public Object searchByKeyword(String keyword) {
        keyword = "%" + keyword + "%";
        QueryWrapper productQW = new QueryWrapper();
        QueryWrapper storeQW = new QueryWrapper();
        QueryWrapper videoQW = new QueryWrapper();
        productQW
                .select()
                .from(PRODUCTS)
                .where(PRODUCTS.NAME.like(keyword));
        storeQW
                .select()
                .from(STORES)
                .where(STORES.NAME.like(keyword));
        videoQW
                .select()
                .from(VIDEOS)
                .where(VIDEOS.TITLE.like(keyword));
        List<Products> productsList = productsMapper.selectListByQuery(productQW);
        List<Stores> storesList = storesMapper.selectListByQuery(storeQW);
        List<Videos> videosList = videosMapper.selectListByQuery(videoQW);
        Search search =new Search();
        search.setProducts(productsList);
        search.setStores(storesList);
        search.setVideos(videosList);
        return Result.success(search);
    }

    @Override
    public Object recommend(){
        int userId = getUserId();
        QueryWrapper cartQW = new QueryWrapper();
        QueryWrapper orderQW = new QueryWrapper();
        QueryWrapper favoriteQW = new QueryWrapper();
        cartQW.from(CART_ITEMS)
                .where(CART_ITEMS.USER_ID.eq(userId));
        orderQW.from(ORDER_ITEMS)
                .join(ORDERS).on(ORDER_ITEMS.ORDER_ID.eq(ORDERS.ORDER_ID))
                .where(ORDERS.USER_ID.eq(userId))
                .orderBy(ORDER_ITEMS.QUANTITY,false);
        favoriteQW.from(FAVORITES)
                .where(FAVORITES.USER_ID.eq(userId))
                .and(FAVORITES.TYPE.eq("product"));
        List<CartItems> cartItemsList = cartItemsMapper.selectListByQuery(cartQW);
        List<OrderItems> orderItemsList = orderItemsMapper.selectListByQuery(orderQW);
        List<Favorites> favoritesList = favoritesMapper.selectListByQuery(favoriteQW);
        List<Products> productsList = new ArrayList<>();
        for(Favorites favorites : favoritesList){
            Products products = productsMapper.selectOneById(favorites.getProductId());
            if(products.getDelete()==0)
                productsList.add(products);
        }
        for(OrderItems orderItems : orderItemsList){
            Products products = productsMapper.selectOneById(orderItems.getProductId());
            if(!productsList.contains(products)&&products.getDelete()==0)
                productsList.add(products);
        }
        for (CartItems cartItems : cartItemsList){
            Products products = productsMapper.selectOneById(cartItems.getProductId());
            while(productsList.contains(products))
                if(products.getDelete()==0)
                    productsList.remove(products);
        }
        if (productsList.isEmpty()){
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper
                    .select(PRODUCTS.ALL_COLUMNS)
                    .from(PRODUCTS)
                    .where(PRODUCTS.DELETE.eq(0))
                    .orderBy(PRODUCTS.SALES_COUNT,false);
            return Result.success(productsMapper.selectListByQuery(queryWrapper));
        }
        return Result.success(productsList);
    }
}
